<!--
 * @Author: Easycome 2684545336@qq.com
 * @Date: 2025-04-19 00:12:25
 * @LastEditors: Easycome 2684545336@qq.com
 * @LastEditTime: 2025-04-19 23:09:19
 * @FilePath: \yupao-frontend-master\src\components\MyDynamicList.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="my-dynamic-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-if="dynamicList.length === 0 && !loading" class="empty-container">
          <van-empty description="暂无动态内容" />
          <van-button type="primary" size="small" @click="toCreateDynamic">发布动态</van-button>
        </div>
        
        <!-- 动态列表项 -->
        <div v-for="item in dynamicList" :key="item.dynamicId" class="dynamic-item">
          <!-- 用户信息区 -->
          <div class="user-info-container">
            <img :src="item.user.avatarUrl || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'" class="avatar" />
            <div class="user-info-text">
              <div class="username">{{ item.user.username }}</div>
              <div class="time">{{ formatTime(item.createTime) }}</div>
            </div>
            <div class="options">
              <van-icon name="delete-o" @click="confirmDelete(item.dynamicId)" />
            </div>
          </div>
          
          <!-- 动态内容区 -->
          <div class="content-container" @click="viewDynamicDetail(item.dynamicId)">
            <div class="text-content">{{ item.content }}</div>
            
            <!-- 图片区 -->
            <div v-if="item.mediaUrls && item.mediaUrls.length > 0" class="media-container">
              <van-image-preview
                v-model:show="item.showImagePreview"
                :images="item.mediaUrls"
                :start-position="item.currentImageIndex"
                :show-index="true"
              />
              <div :class="['image-grid', `image-grid-${Math.min(item.mediaUrls.length, 9)}`]">
                <div
                  v-for="(url, index) in item.mediaUrls"
                  :key="index"
                  class="image-item"
                  @click.stop="previewImage(item, index)"
                >
                  <van-image
                    :src="url"
                    fit="cover"
                    radius="4"
                    lazy-load
                  />
                </div>
              </div>
            </div>
          </div>
          
          <!-- 操作区 -->
          <div class="action-container">
            <div class="action-item" @click="toggleLike(item)">
              <van-icon :name="item.hasLiked ? 'like' : 'like-o'" :color="item.hasLiked ? '#ee0a24' : ''" />
              <span>{{ item.likeCount || 0 }}</span>
            </div>
            <div class="action-item" @click="viewDynamicDetail(item.dynamicId)">
              <van-icon name="chat-o" />
              <span>{{ item.commentCount || 0 }}</span>
            </div>
            <div class="action-item">
              <van-icon name="share-o" />
              <span>{{ item.shareCount || 0 }}</span>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 删除确认对话框 -->
    <van-dialog
      v-model:show="deleteConfirmVisible"
      title="删除动态"
      show-cancel-button
      @confirm="deleteConfirmed"
    >
      <p class="delete-confirm-text">确定要删除这条动态吗？</p>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { 
  showSuccessToast, 
  showFailToast, 
  showLoadingToast 
} from 'vant';
import { 
  getMyDynamicList, 
  deleteDynamic, 
  likeDynamic,
  unlikeDynamic,
  getCommentList,
  addComment
} from '../services/community';

const props = defineProps({
  userId: {
    type: [Number, String],
    default: null
  }
});

// 数据模型
const dynamicList = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const deleteConfirmVisible = ref(false);
const pendingDeleteId = ref(null);

const router = useRouter();

onMounted(async () => {
  if (props.userId) {
    await loadMyDynamicList();
  }
});

// 监听userId变化
watch(() => props.userId, async (newVal) => {
  if (newVal) {
    currentPage.value = 1;
    dynamicList.value = [];
    finished.value = false;
    await loadMyDynamicList();
  }
});

// 加载个人动态列表
const loadMyDynamicList = async (isRefresh = false) => {
  if (!props.userId) return;
  
  if (isRefresh) {
    currentPage.value = 1;
    dynamicList.value = [];
    finished.value = false;
  }
  
  try {
    loading.value = true;
    
    const response = await getMyDynamicList({
      current: currentPage.value,
      pageSize: pageSize.value,
      sortField: 'create_time',
      sortOrder: 'desc'
    });
    
    console.log("加载我的动态列表响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        if (response.data && response.data.records) {
          // 直接使用服务器返回的数据，添加UI所需的额外属性
          const newData = response.data.records.map(item => ({
            ...item,
            showImagePreview: false,
            currentImageIndex: 0
          }));
          
          // 处理分页逻辑
          if (isRefresh || currentPage.value === 1) {
            // 完全重置列表，使用服务器数据
            dynamicList.value = newData;
          } else {
            // 追加新数据，但避免重复
            const existingIds = dynamicList.value.map(item => item.dynamicId);
            const uniqueNewData = newData.filter(item => !existingIds.includes(item.dynamicId));
            dynamicList.value = [...dynamicList.value, ...uniqueNewData];
          }
          
          // 更新分页信息
          currentPage.value++;
          
          // 判断是否已加载全部数据
          if (newData.length === 0 || dynamicList.value.length >= response.data.total) {
            finished.value = true;
          }
          
          console.log(`加载我的动态: 总数=${response.data.total}, 当前页=${currentPage.value-1}, 记录数=${newData.length}, 列表长度=${dynamicList.value.length}`);
        } else {
          showFailToast("返回数据格式异常");
          finished.value = true;
        }
        break;
        
      case 50000: // 系统内部异常，视为错误
        showFailToast("获取动态列表时发生系统异常");
        console.error("获取动态列表返回50000错误:", response);
        finished.value = true;
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        finished.value = true;
        break;
        
      case 40001: // 请求数据为空
        // 没有动态数据，设置空列表
        dynamicList.value = [];
        finished.value = true;
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        finished.value = true;
        break;
        
      case 40101: // 无权限
        showFailToast("您没有权限查看");
        finished.value = true;
        break;
        
      default:
        showFailToast(response.message || response.description || "获取动态列表失败");
        finished.value = true;
    }
  } catch (error) {
    console.error("获取动态列表失败", error);
    showFailToast("获取动态列表失败，请稍后重试");
    finished.value = true;
  } finally {
    loading.value = false;
    if (isRefresh) {
      refreshing.value = false;
    }
  }
};

// 下拉刷新
const onRefresh = async () => {
  await loadMyDynamicList(true);
};

// 上拉加载更多
const onLoad = async () => {
  if (!finished.value) {
    await loadMyDynamicList();
  }
};

// 跳转到发布动态
const toCreateDynamic = () => {
  router.push('/community');
};

// 预览图片
const previewImage = (item, index) => {
  item.currentImageIndex = index;
  item.showImagePreview = true;
};

// 查看动态详情
const viewDynamicDetail = (dynamicId) => {
  // 跳转到社区页面查看详情和评论
  router.push({
    path: '/community',
    query: { dynamicId }
  });
};

// 确认删除动态
const confirmDelete = (dynamicId) => {
  pendingDeleteId.value = dynamicId;
  deleteConfirmVisible.value = true;
};

// 确认删除后执行删除
const deleteConfirmed = async () => {
  if (!pendingDeleteId.value) return;
  
  try {
    const loading = showLoadingToast({
      message: "删除中...",
      forbidClick: true
    });
    
    const response = await deleteDynamic(pendingDeleteId.value);
    console.log("删除动态响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        showSuccessToast("删除成功");
        
        // 从列表中移除已删除的动态
        dynamicList.value = dynamicList.value.filter(
          item => item.dynamicId !== pendingDeleteId.value
        );
        break;
        
      case 50000: // 系统内部异常，但操作可能已成功
        showSuccessToast("删除可能已成功，但系统返回警告");
        
        // 从列表中移除动态（假设已删除）
        dynamicList.value = dynamicList.value.filter(
          item => item.dynamicId !== pendingDeleteId.value
        );
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        break;
        
      case 40001: // 请求数据为空
        showFailToast("动态不存在或已被删除");
        // 从列表中移除不存在的动态
        dynamicList.value = dynamicList.value.filter(
          item => item.dynamicId !== pendingDeleteId.value
        );
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        break;
        
      case 40101: // 无权限
        showFailToast("您没有权限删除此动态");
        break;
        
      case 50001: // 插入数据失败
        showFailToast("数据库操作失败，请稍后重试");
        break;
        
      default:
        showFailToast(response.message || response.description || "删除失败");
    }
    
    loading.close();
  } catch (error) {
    console.error("删除动态失败", error);
    showFailToast("删除失败，请稍后重试");
  } finally {
    pendingDeleteId.value = null;
  }
};

// 点赞/取消点赞动态
const toggleLike = async (item) => {
  try {
    const loading = showLoadingToast({
      message: item.hasLiked ? "取消点赞中..." : "点赞中...",
      forbidClick: true
    });
    
    const response = item.hasLiked 
      ? await unlikeDynamic(item.dynamicId)
      : await likeDynamic(item.dynamicId);
    
    console.log("点赞/取消点赞响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        // 更新UI显示
        item.hasLiked = !item.hasLiked;
        item.likeCount = item.hasLiked 
          ? (item.likeCount + 1) 
          : (item.likeCount > 0 ? item.likeCount - 1 : 0);
        
        // 操作成功提示
        const actionText = item.hasLiked ? "点赞成功" : "取消点赞成功";
        showSuccessToast(actionText);
        break;
        
      case 50000: // 系统内部异常，但操作可能已成功
        // 如果是50000错误码，视为成功但有警告
        showSuccessToast("操作已执行，但系统返回警告");
        
        // 更新UI显示
        item.hasLiked = !item.hasLiked;
        item.likeCount = item.hasLiked 
          ? (item.likeCount + 1) 
          : (item.likeCount > 0 ? item.likeCount - 1 : 0);
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        break;
        
      case 40001: // 请求数据为空
        showFailToast("动态不存在或已被删除");
        // 从列表中移除不存在的动态
        dynamicList.value = dynamicList.value.filter(
          dynItem => dynItem.dynamicId !== item.dynamicId
        );
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        break;
        
      case 40101: // 无权限
        showFailToast("您没有操作权限");
        break;
        
      case 50001: // 插入数据失败
        showFailToast("数据库操作失败，请稍后重试");
        break;
        
      default:
        showFailToast(response.message || response.description || "操作失败");
    }
    
    loading.close();
  } catch (error) {
    console.error("点赞操作失败", error);
    showFailToast("操作失败，请稍后重试");
  }
};

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 大于30天，显示具体日期
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
};
</script>

<style scoped>
.my-dynamic-list {
  padding: 0;
  background-color: #f7f8fa;
  min-height: 100%;
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  gap: 16px;
}

.dynamic-item {
  margin-bottom: 10px;
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 0;
  box-shadow: none;
  border-bottom: 1px solid #f2f2f2;
}

/* 用户信息区 */
.user-info-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.user-info-text {
  flex: 1;
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.time {
  font-size: 12px;
  color: #999;
}

.options {
  font-size: 18px;
  color: #999;
}

/* 内容区 */
.content-container {
  margin-bottom: 10px;
}

.text-content {
  font-size: 15px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 10px;
  word-break: break-all;
}

/* 媒体区 */
.media-container {
  margin-top: 8px;
}

.image-grid {
  display: grid;
  grid-gap: 4px;
}

.image-grid-1 {
  grid-template-columns: 1fr;
}

.image-grid-2, .image-grid-4 {
  grid-template-columns: repeat(2, 1fr);
}

.image-grid-3, .image-grid-5, .image-grid-6, .image-grid-7, .image-grid-8, .image-grid-9 {
  grid-template-columns: repeat(3, 1fr);
}

.image-item {
  position: relative;
  padding-top: 100%;
  overflow: hidden;
}

.image-item :deep(.van-image) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 操作区 */
.action-container {
  display: flex;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
}

.action-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #666;
  gap: 6px;
}

.delete-confirm-text {
  padding: 20px;
  text-align: center;
  color: #666;
}
</style> 